package com.heima.wemedia.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import org.springframework.asm.Handle;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WmTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是网关发来的请求，不是就拦截
        String requestFrom = request.getHeader("X-Request-From");
        if(!StrUtil.equals(requestFrom,"heima-leadnews-wemedia-gateway")){
            response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
            return false;
        }
        //得到header中的userId信息
        String userId = request.getHeader("userId");
        if (StrUtil.isNotEmpty(userId)) {
            //把用户id存入threadloacl中
            WmUser wmUser = new WmUser();
            wmUser.setId(Convert.toInt(userId));
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocalUtil.clear();
    }
}
